//
//  ARIndexWorkDetailController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/14.
//

import UIKit
import SnapKit
import AttributedString
import JKSwiftExtension

/// 首页进来的作品详情页
class ARIndexWorkDetailController: ARBaseViewController {

    // MARK: - Property
    
    let workId: String
    let viewModel: ARWorkDetailViewModel
    let style = ARWorkDetailPathStyle.index
    
    private static let cellReuseId = "ar.indexWorkDetailPage.cellReuseId"
    private static let commentCellReuseId = "ar.indexWorkDetailPage.commentCellReuseId"
    
    // MARK: - Init
    
    init(workId: String) {
        self.workId = workId
        self.viewModel = ARWorkDetailViewModel(workId: workId, style: self.style)
        
        super.init(nibName: nil, bundle: nil)
        
        self.fd_prefersNavigationBarHidden = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        loadData()
    }
    
    // MARK: - UI
    
    private func setupUI() {
        
        self.view.backgroundColor = .white
        
        tableHeaderView.addSubview(picsCollectionView)
        tableHeaderView.addSubview(workContentView)
        tableHeaderView.addSubview(workInfoContainerView)
        
        self.view.addSubview(tableView)
        tableView.tableHeaderView = tableHeaderView
        self.view.addSubview(backBtn)
        
        self.addChild(inputVc)
        self.view.addSubview(inputVc.view)
        
        picsCollectionView.snp.makeConstraints { make in
            make.top.right.left.equalToSuperview()
            make.width.equalTo(ARHelper.screenWidth())
            make.height.equalTo(ARHelper.screenWidth() * (367.0 / 375.0))
        }
        workInfoContainerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.centerY.equalTo(picsCollectionView.snp.bottom)
            make.height.equalTo(ARHelper.screenWidth() * (156.0 / 375.0))
        }
        workContentView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(picsCollectionView.snp.bottom)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(inputVc.view.snp.top)
        }
        
        backBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(8 + ARHelper.statusBarHeight())
            make.width.height.equalTo(28)
        }
        
        inputVc.view.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-ARHelper.safeBottomHeight())
            // 自适应高度
        }
        
        // 初始高度
        let height = tableHeaderView.systemLayoutSizeFitting(.init(width: ARHelper.screenWidth(), height: CGFloat.greatestFiniteMagnitude)).height
        tableHeaderView.frame = .init(x: 0, y: 0, width: ARHelper.screenWidth(), height: height)
    }
    
    // MARK: - Action
    
    @objc private func likeBtnCliked(_ sender: UIButton) {
        self.ar.showLoading()
        viewModel.likeOrUnLikeWork { [weak self] err in
            guard let self = self else {
                return
            }
            self.ar.hideHUD()
            if let err = err {
                self.ar.makeToast(err.localizedDescription)
                return
            }
            
            // 成功 - 更新
            self.updateVcValue()
        }
    }
    
    // MARK: -
    
    private func loadData() {
        self.ar.showLoading()
        viewModel.fetchWork { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            
            self?.updateVcValue()
        }
    }
    
    /// 更新数据
    private func updateVcValue() {
        guard let work = viewModel.workModel else {
            return
        }
        titleLabel.text = work.workTitle
        // 评论数
        commentCountBtn.setTitle(String(work.comments?.count ?? 0), for: .normal)
        // 点赞
        likeBtn.setTitle(String(work.likeNum ?? 0), for: .normal)
        likeBtn.isSelected = (work.isLike ?? false)
        // 标题
        let content = work.workDescription
        
        let contentAttri = ASAttributedString(string: content,
                        .font(ARHelper.font(14, weight: .regular)),
                        .foreground(UIColor(hexString: "#565656") ?? .black),
                        .paragraph(.alignment(.left), .minimumLineHeight(21), .maximumLineHeight(21)))
        workContentLabel.attributed.text = contentAttri
        
        // 更新高度
        let height = tableHeaderView.systemLayoutSizeFitting(.init(width: ARHelper.screenWidth(), height: CGFloat.greatestFiniteMagnitude)).height
        tableHeaderView.frame = .init(x: 0, y: 0, width: ARHelper.screenWidth(), height: height)
        
        picsCollectionView.reloadData()
        tableView.reloadData()
    }
    
    // MARK: - Lazy
    
    private lazy var backBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(ar_transitionToBack), for: .touchUpInside)
        btn.setImage(.init(named: "common_nav_new_back_white_icon"), for: .normal)
        return btn
    }()
    
    private lazy var tableHeaderView: UIView = {
        let tableHeaderView = UIView()
        tableHeaderView.backgroundColor = .white
        return tableHeaderView
    }()
    
    private lazy var picsCollectionView: UICollectionView = {
        let flow = UICollectionViewFlowLayout()
        flow.itemSize = .init(width: ARHelper.screenWidth(), height: ARHelper.screenWidth() * (367.0 / 375.0))
        flow.scrollDirection = .horizontal
        flow.minimumLineSpacing = 0
        flow.minimumInteritemSpacing = 0
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flow)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: Self.cellReuseId)
        
        collectionView.isPagingEnabled = true
        collectionView.backgroundColor = .white
        return collectionView
    }()

    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = ARHelper.font(18, weight: .medium)
        label.textColor = .white
        return label
    }()
    
    private lazy var likeBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(.init(named: "common_like_btn_normal"), for: .normal)
        btn.setImage(.init(named: "common_like_btn_selected"), for: .selected)
        btn.titleLabel?.font = ARHelper.font(18, weight: .medium)
        btn.setTitleColor(.white, for: .normal)
        btn.addTarget(self, action: #selector(likeBtnCliked(_:)), for: .touchUpInside)
        btn.jk.setImageTitleLayout(.imgLeft, spacing: 4)
        return btn
    }()
    
    /// 评论数
    private lazy var commentCountBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(.init(named: "post_detail_commentCount_icon"), for: .normal)
        btn.titleLabel?.font = ARHelper.font(18, weight: .medium)
        btn.setTitleColor(.white, for: .normal)
        
        btn.isUserInteractionEnabled = false
        btn.jk.setImageTitleLayout(.imgLeft, spacing: 4)
        return btn
    }()
    
    private lazy var workInfoContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        
        let bgImageView = UIImageView(image: .init(named: "post_detail_info_bg"))
        let starView = UIImageView(image: .init(named: "index_star"))
        
        view.addSubview(bgImageView)
        view.addSubview(titleLabel)
        view.addSubview(starView)
        view.addSubview(likeBtn)
        view.addSubview(commentCountBtn)
        
        bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(ARHelper.screenWidth())
            make.height.equalTo(ARHelper.heightScale(156.0))
        }
        
        titleLabel.snp.makeConstraints { make in
            make.bottom.equalTo(view.snp.centerY).offset(ARHelper.heightScale(-10.0))
            make.left.equalToSuperview().offset(32)
            make.right.equalToSuperview().offset(-32)
        }
        
        starView.snp.makeConstraints { make in
            make.width.equalTo(143.0)
            make.height.equalTo(24.0)
            make.left.equalTo(titleLabel)
            make.top.equalTo(view.snp.centerY).offset(ARHelper.heightScale(8))
        }
        
        likeBtn.snp.makeConstraints { make in
            make.centerY.equalTo(starView)
            make.right.equalToSuperview().offset(-32)
        }
        
        commentCountBtn.snp.makeConstraints { make in
            make.centerY.equalTo(starView)
            make.right.equalTo(likeBtn.snp.left).offset(-24)
        }
        
        return view
    }()
    
    private lazy var workContentLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        return label
    }()
    
    /// 作品内容的View
    private lazy var workContentView: UIView = {
        
        let separatorView = UIView()
        separatorView.backgroundColor = .init(hexString: "#F6F7F8")
        
        let view = UIView()
        view.backgroundColor = .white
        
        view.addSubview(separatorView)
        view.addSubview(workContentLabel)
        
        separatorView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(8)
        }
        
        workContentLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(32)
            make.width.equalToSuperview().offset(-32)
            make.bottom.equalTo(separatorView.snp.top).offset(-24)
            make.top.equalToSuperview().offset(16 + 78)
        }
        
        return view
    }()
    
    private lazy var tableView: UITableView = {
        var tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = .clear
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = true
        tableView.register(ARWorkCommentCell.self, forCellReuseIdentifier: Self.commentCellReuseId)
        tableView.estimatedRowHeight = 116
        return tableView
    }()
    
    private lazy var inputVc: ARCommentInputController = {
        let vc = ARCommentInputController(functions: [.text])
        vc.separatorLine.isHidden = false
        vc.delegate = self
        return vc
    }()
}

// MARK: -

extension ARIndexWorkDetailController: UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Self.cellReuseId, for: indexPath)
        
        // 判断是否有UIImageView
        var imageView = cell.viewWithTag(1124)
        if imageView == nil {
            imageView = UIImageView()
            imageView?.tag = 1124
            cell.contentView.addSubview(imageView!)
            imageView!.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            
            imageView?.contentMode = .scaleAspectFill
            imageView?.layer.masksToBounds = true
        }
        
        if let patchs = self.viewModel.workModel?.realPicsPath() {
            (imageView as? UIImageView)?.ar.setImage(patchs[indexPath.item])
        }
        
        return cell
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.viewModel.workModel?.realPicsPath()?.count ?? 0
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
}

extension ARIndexWorkDetailController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.comment.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = viewModel.comment[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: Self.commentCellReuseId, for: indexPath) as! ARWorkCommentCell
        cell.celldData = model
        cell.selectionStyle = .none
        
        cell.likeBtnClickedCallback = { [weak self] aCell in
            guard let cellData = aCell.celldData else {
                return
            }
            self?.ar.showLoading()
            self?.viewModel.likeOrUnLikeComment(cellData.commentModel.id, like: !cellData.commentModel.isLike, completion: { err in
                self?.ar.hideHUD()
                if let err = err {
                    self?.ar.makeToast(err.localizedDescription)
                    return
                }
                
                // 成功 - 刷新
                aCell.celldData = cellData
            })
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = viewModel.comment[indexPath.row]
        return model.cellHeight
    }
    
}

extension ARIndexWorkDetailController: ARCommentInputControllerDelegate {
    
    func inputVc(_ vc: ARCommentInputController, recordGestureDidChange gesture: UILongPressGestureRecognizer) {
        // Do nothing...
    }
    
    
    func inputVc(_ vc: ARCommentInputController, sentVale: ARCommentInputController.InputValue) {
        
        if case.text(let sendText) = sentVale {
            // 只处理text
            ARHelper.window().ar.showLoading()
            self.viewModel.postTextComment(sendText) { [weak self] err in
                guard let self = self else {
                    return
                }
                ARHelper.window().ar.hideHUD()
                if let err = err {
                    ARHelper.window().ar.makeToast(err.localizedDescription)
                    return
                }
                // 成功
                self.inputVc.clearText()
                self.updateVcValue()
                DispatchQueue.main.async {
                    self.tableView.jk.scrollToBottom(animated: true)
                }
            }
        }
        
    }
    
}
